<template>
  <!-- 子机构展开行表格 -->
  <div>
    <div class="insitiutions-expend" v-cloak>
      <div v-if="son.length > 0" class="table-content">
        <Table
          :columns="columns10"
          :data="son"
          :show-header="false"
          width="100%"
        ></Table>
        <!-- <span @click="showNext" v-if="!isShowAll && allList.length > 0" class="btn"> -->
        <span @click="loadMore" v-if="isShowAll" class="btn">
          加载更多
          <Icon type="md-arrow-round-down" class="icon" />
        </span>
      </div>

      <!-- 编辑子机构 -->
      <Modal
       :mask-closable="false"
        v-model="modal1"
        width="800"
        title="编辑子机构"
        @on-visible-change="JGVisibleChange"
      >
        <p class="message">基本信息</p>
        <Form
          v-if="modal1"
          :model="formLeft"
          label-position="right"
          :label-width="100"
          ref="JGForm"
          :rules="ruleValidate"
        >
          <Row :gutter="18">
            <Col span="12">
              <FormItem label="org_id:" prop="org_id">
                <Input v-model="formLeft.org_id" :disabled="formLeft.isEdit"/>
              </FormItem>
            </Col>
            <Col span="6">
              <Button
                type="primary"
                @click="searchOrgID"
                v-if="!formLeft.isEdit"
                >搜索</Button
              >
            </Col>
          </Row>
          <Row>
            <Col span="12">
              <FormItem label="org_name:" prop="org_name">
                <Input v-model="formLeft.org_name" />
              </FormItem>
              <FormItem label="country:" prop="country">
                <Input v-model="formLeft.country" />
              </FormItem>
              <FormItem label="province:" prop="province">
                <Input v-model="formLeft.province" />
              </FormItem>
              <FormItem label="city:" prop="city">
                <Input v-model="formLeft.city" />
              </FormItem>
              <FormItem label="street:" prop="street">
                <Input v-model="formLeft.street" />
              </FormItem>
              <FormItem label="机构类型:" prop="org_type">
                <Select
                  v-model="formLeft.org_type"
                  placeholder="请选择机构类型"
                >
                  <Option value="高校">高校</Option>
                  <Option value="企业">企业</Option>
                  <Option value="医院">医院</Option>
                  <Option value="研究机构">研究机构</Option>
                  <Option value="其他">其他</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="机构名称:" prop="org_name_cn">
                <Input v-model="formLeft.org_name_cn" />
              </FormItem>
              <FormItem label="国家:" prop="country_cn">
                <Input v-model="formLeft.country_cn" />
              </FormItem>
              <FormItem label="省份:" prop="province_cn">
                <Input v-model="formLeft.province_cn" />
              </FormItem>
              <FormItem label="城市:" prop="city_cn">
                <Input v-model="formLeft.city_cn" />
              </FormItem>
              <FormItem label="街道:" prop="street_cn">
                <Input v-model="formLeft.street_cn" />
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div slot="footer">
          <Button type="text" @click="cancel">取消</Button>
          <Button type="primary" @click="ok">保存</Button>
        </div>
      </Modal>
      <!-- 查看记录 -->
      <Modal
       :mask-closable="false"
        width="60%"
        v-model="record"
        title="查看记录"
        @on-visible-change="JLVisibleChange"
        footer-hide
      >
        <Table :columns="columnsrecord1" :data="datarecord1"></Table>
        <Page
          class="td-left"
          :total="recordTotal"
          show-total
          show-elevator
          :page-size="recordPageSize"
          :page="recordPage"
          :current="recordPage"
          @on-change="Recordchangedata"
          show-sizer
          @on-page-size-change="RecordchangePagesize"
        />
        <div style="clear:both"></div>
      </Modal>
    </div>
  </div>
</template>
<script>
import {
  getDatalist,
  deleteAgency,
  recordAgency,
  addOrUpdateJG
} from '@/api/institutions'
import loadingUtils from './loading.js'
export default {
  props: {
    row: Object
  },
  data () {
    return {
      // loading: true,
      formLeft: {
        org_id: '',
        org_name: '',
        country: '',
        province: '',
        city: '',
        street: '',
        org_name_cn: '',
        country_cn: '',
        province_cn: '',
        city_cn: '',
        street_cn: '',
        org_type: ''
      },
      son: [],
      switchList:false,//是否加载更多
      modal1: false,
      columns10: [
        {
          title: '机构ID',
          width: 250,
          key: 'org_id'
        },
        {
          title: '机构名称',
          // align: "center",
          width: 300,
          key: 'org_name'
        },
        {
          title: '城市',
          // align: "center",
          width: 260,
          key: 'city'
        },
        {
          title: '国家',
          // align: "center",
          width: 240,
          key: 'country'
        },
        {
          title: '类型',
          // align: "center",
          width: 120,
          align: 'left',
          key: 'org_type'
        },
        {
          title: '操作',
          align: 'left',
          // width: 400,
          render: (h, params) => {
            let add = h(
              'Button',
              {
                props: {
                  type: 'text'
                  // icon: "ios-trash-outline"
                },
                style: {
                  color: '#2d8cf0',
                  marginLeft: '48px'
                },
                on: {
                  click: () => {}
                }
              },
              '  '
            )

            let edit = h(
              'Button',
              {
                props: {
                  type: 'text'
                  // icon: "ios-create-outline"
                },
                style: {
                  color: '#2d8cf0',
                  padding: '0',
                  marginRight: '19px'
                },
                on: {
                  click: () => {
                    // 设置表单得校验规则
                    this.ruleValidate = {
                      org_id: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      org_name: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      country: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      province: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      city: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      street: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      org_name_cn: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      country_cn: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      province_cn: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      city_cn: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      street_cn: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ],
                      org_type: [
                        {
                          required: true,
                          message: '此项为必填项',
                          trigger: 'change'
                        }
                      ]
                    }
                    this.modal1 = true
                    const temp = params.row
                    // 对应赋值
                    for (const key in this.formLeft) {
                      if (key != 'org_parent_id') { this.formLeft[key] = temp[key]?  temp[key] + '' || '':"" }
                    }
                    this.formLeft.disabled = false
                    this.formLeft.isEdit = true
                    this.switchList = false
                    // this.showNext()
                  }
                }
              },
              '编辑'
            )

            let del = h(
              'Poptip',
              {
                props: {
                  confirm: true,
                  title: '你确定移除吗?',
                  transfer: true
                },
                style: {
                  // marginRight: "5px"
                },
                on: {
                  'on-ok': async () => {
                    const { data: res } = await deleteAgency({
                      org_id: params.row.org_id
                    })
                    if (res.code == 0) {
                      if (res.message) { return this.$Message.warning(res.message) } // 成功的提示
                      this.$Message.success('移除子机构成功') // 成功的提示
                      this.switchList = false
                      this.pageNum = 1
                      this.showNext()
                      // this.getDatalistL()
                    }
                  }
                }
              },
              [
                h(
                  'Button',
                  {
                    props: {
                      type: 'text',
                      size: 'small'
                    },
                    style: {
                      color: 'rgb(45, 140, 240)',
                      padding: '0',
                      marginRight: '19px'
                    }
                  },
                  '移除'
                )
              ]
            )

            let task = h(
              'Button',
              {
                props: {
                  type: 'text'
                  // icon: "ios-search-outline"
                },
                style: {
                  color: '#2d8cf0',
                  padding: '0'
                },
                on: {
                  click: () => {
                    this.record = true
                    this.getRecord(params.row.org_id)
                  }
                }
              },
              '查看记录'
            )
            let option = []
            option.push(add)
            option.push(edit)
            option.push(del)
            option.push(task)
            return h('div', option, {
              class: 'aaaaa'
            })
          }
        }
      ],
      allList: [], // 所有数据
      pageSize: 5, // 每次显示多少数据
      pageNum: 1, // 当前页码
      isShowAll: false, // 判断是否已显示完所有的数据
      flag: false,
      last_page: 1,
      // 查看记录
      record: false,
      columnsrecord1: [
        {
          title: '编辑人',
          // align: "center",
          key: 'admin_name'
        },
        {
          title: '编辑内容',
          // align: "center",
          key: 'remark',
          render: (h, params) => {
            let strs = []
            let i = 0
            for (let ky in params.row.remark) {
              i++
               strs.push(h('div',
                [ h('span',i + '.'),
                  h('span', { style: { color: '#3a64ff' } }, this.zd[ky]),
                  h('span', { style: { color: '#000' } }, '由'),
                  h('span', { style: { color: '#f3775e' } },  params.row.remark[ky][0]?params.row.remark[ky][0]:"空"),
                  h('span', { style: { color: '#000' } }, '修改为'),
                  h('span', { style: { color: '#59c692' } }, params.row.remark[ky][1])
                ]
              ))
              // strs.push([

              //     h('span', { style: { color: '#3a64ff' } }, this.zd[ky]),
              //     h('span', { style: { color: '#000' } }, '由'),
              //     h('span', { style: { color: '#f3775e' } }, params.row.remark[ky][0]),
              //     h('span', { style: { color: '#000' } }, '修改为'),
              //     h('span', { style: { color: '#59c692' } }, params.row.remark[ky][1])
              //   ])
            //  strs.push(`将${this.zd[ky]}从${params.row.remark[ky][0]}修改为${params.row.remark[ky][1]}`)
            }
            // return h('span', strs.join(';'))
            return h('div',strs)
          }
        },
        {
          title: '更新时间',
          // align: "center",
          key: 'updated_at'
        }
      ],
      datarecord1: [],
      recordPage: 1,
      recordPageSize: 10,
      recordTotal: 0
    }
  },
  async created () {
    console.log('table-list onCreated')
    this.formLeft.org_parent_id = this.row.org_id
    this.showNext()
    // this.getDatalistL()
  },
  mounted () {
    this.zd = {
      org_name: '机构名称',
      country: '国家',
      province: '省份',
      city: '城市',
      street: '街道',
      org_name_cn: '机构名称',
      country_cn: '国家',
      province_cn: '省份',
      city_cn: '城市',
      street_cn: '街道',
      org_type: '机构类型'
    }
  },
  methods: {
    // 分配数据的方法
    // showNext (row) {
    //   if (this.flag) return
    //   this.flag = true
    //   if (this.allList.length > 0) {
    //     // 页码自加1
    //     this.pageNum++
    //     // 计算截取的开始位置的索引
    //     const start = (this.pageNum - 1) * this.pageSize
    //     // 计算截取的结束位置的索引
    //     let end = this.pageNum * this.pageSize
    //     end = this.allList.length < end ? this.allList.length : end
    //     // console.log(start);
    //     // console.log(end);
    //     this.son.push(...this.allList.slice(start, end))
    //   } else {
    //     const { data } = row
    //     this.allList = data
    //     // 计算截取的开始位置的索引
    //     const start = (this.pageNum - 1) * this.pageSize
    //     // 计算截取的结束位置的索引
    //     let end = this.pageNum * this.pageSize
    //     end = this.allList.length < end ? this.allList.length : end
    //     this.son = this.allList.slice(start, end)
    //   }
    //   // 每次判断一下数据是否已经显示完成
    //   this.isShowAll = this.allList.length === this.son.length
    //   setTimeout(() => {
    //     this.flag = false
    //   }, 10)
    // },
    loadMore() {
      this.switchList = true
      this.pageNum += 1
      this.showNext() 
    },
    showNext () {
      let list = []
      let params = {
        org_id: this.row.org_id,
        page:this.pageNum,
        page_size: this.pageSize,
      }
      getDatalist(params).then(res=>{
        list = res.data.data.data
        if (this.switchList) {
          this.son.push(...list)
        } else {
          this.son = list
        }
        if (this.son.length < res.data.data.total) {
          this.isShowAll = true
        } else {
          this.isShowAll = false
        }
      })
    },
     
    // async getDatalistL (page) {
      // let params = {
      //   org_id: this.row.org_id,
      //   page:page?page:this.pageNum,
      //   page_size: this.pageSize
      // }
    //   console.log(params)
    //   const {
    //     data:{data:res}
    //   } = await getDatalist(params)
    //     // console.timeEnd('结束')
    //   // this.allList = []
    //   this.last_page = res.last_page
    //   console.log(res.last_page,'last_page')
    //   // console.log(res,'res------')
    //   // this.son = res.data
    //   return res.data
    //   // this.showNext(res)
    //   // this.loading = false
    // },
    // 保存
    async ok () {
      try {
        const validate = await this.$refs.JGForm.validate().catch(res => res)
        // 判断表单验证是否通过 不通过的话给与提示
        if (!validate) return
        // 设置请求的参数对象
        const temp = Object.assign({}, this.formLeft)
        delete temp.org_id
        temp.method = 'add'
        if (this.formLeft.isEdit) temp.method = 'edit'
        // 发送新增的请求
        const { data: res } = await addOrUpdateJG({
          org_id: this.formLeft.org_id,
          data: temp
        })

        // 判断新增是否成功
        if (res.code === 0) {
          this.modal1 = false // 关闭弹窗
          // this.getDatalistL() // 重新获取表格数据
          this.pageNum = 1
          this.showNext() // 重新获取表格数据
          this.$Message.success('修改机构信息成功') // 给与成功的提示
          // this.updateshow = true
          // this.showNext() 
        }
      } catch (error) {
        this.$Message.success('新增主机构失败：' + error)
      }
    },
    // 关闭子主机构的新增弹窗
    cancel () {
      this.modal1 = false
    },
    JGVisibleChange (flag) {
      if (flag) return
      this.formLeft.org_id = ''
      this.formLeft.org_name = ''
      this.formLeft.country = ''
      this.formLeft.province = ''
      this.formLeft.city = ''
      this.formLeft.street = ''
      this.formLeft.org_name_cn = ''
      this.formLeft.country_cn = ''
      this.formLeft.province_cn = ''
      this.formLeft.city_cn = ''
      this.formLeft.street_cn = ''
      this.formLeft.org_type = ''
    },
    JLVisibleChange (flag) {
      // 打开弹窗时不需要清楚表单数据
      if (flag) return
      this.recordPage = 1
      this.recordPageSize = 10
      this.recordID = ''
    },
    // 获取详情记录
    async getRecord (id) {
      this.recordID = id
      let params = {
        org_id: id,
        data: { page: this.recordPage, page_size: this.recordPageSize }
      }
      const {
        data: { data: res }
      } = await recordAgency(params)
      this.datarecord1 = res.data
      this.recordTotal = res.total
    },
    Recordchangedata (val) {
      this.recordPage = val
      this.getRecord(this.recordID)
    },
    RecordchangePagesize (val) {
      this.recordPage = 1
      this.recordPageSize = val
      this.getRecord(this.recordID)
    }
  }
}
</script>

<style scoped>
[v-cloak] {
  display: none;
}

.btn {
  width: 100%;
  display: inline-block;
  font-size: 16px;
  font-weight: 700;
  text-align: center;
  margin: 10px 0px 0px 0px;
  cursor: pointer;
  color: #3a64ff;
}
.icon {
  color: #3a64ff;
}
.expand-row {
  margin-bottom: 16px;
}
.icons {
  margin-left: 18px;
  color: #3a64ff;
  cursor: pointer;
}
.insitiutions-expend >>> .ivu-table td {
  background-color: #f8f8f9;
}
.table-content {
  margin: 8px 0
}
</style>
